package com.food.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.food.dao.service.CollectService;
import com.food.dao.service.MbproductService;
import com.food.model.Collect;
import com.food.model.Mbproduct;
import com.food.model.Member;

/**
 * Servlet implementation class mbproductServlet
 */
@WebServlet("/mbproductServlet")
public class mbproductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public mbproductServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try{
			int pid = Integer.parseInt(request.getParameter("pid"));
			HttpSession session = request.getSession();

			Member member = (Member)session.getAttribute("user");
			
			Mbproduct mbproduct = new Mbproduct();
			mbproduct.setPid(pid);
			mbproduct.setMbid(member.getMbid());

			MbproductService mbpService = new MbproductService();
			
			List<Mbproduct> list = mbpService.findProductByMb(mbproduct);
			for(Mbproduct cl:list){
				if(cl.getPid()==pid){
					request.setAttribute("fail", "fail");
					RequestDispatcher rd = request
							.getRequestDispatcher("/ProductPayServlet?pid="+pid);
					rd.forward(request, response);
					return;
				}
				
			}
			
			mbpService.insertMbProduct(mbproduct);
			request.setAttribute("success", "success");
			RequestDispatcher rd = request
					.getRequestDispatcher("/ProductPayServlet?pid="+pid);
			rd.forward(request, response);
			return;
			
			
			}
			catch(Exception e){
				
				RequestDispatcher rd = request
						.getRequestDispatcher("../index.jsp");
				rd.forward(request, response);
				return;
			}
			
		

	}

}
